//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

use git2::{BranchType, Error, Repository};
use serde::Serialize;
use std::path::PathBuf;

#[derive(Serialize)]
struct BranchInfo {
    name: String,
    upstream: String,
    commit_id: String,
    commit_summary: String,
    commit_time: i64,
}

pub fn exec(git_path: PathBuf, remote: &bool) -> Result<(), Error> {
    let repo = Repository::open(git_path);
    if repo.is_err() {
        return Err(repo.err().unwrap());
    }
    let repo = repo.unwrap();

    let option = if *remote {
        Some(BranchType::Remote)
    }else{
        Some(BranchType::Local)
    };
    let branchs = repo.branches(option);
    if branchs.is_err() {
        return Err(branchs.err().unwrap());
    }
    let mut info_list = Vec::new();

    let branchs = branchs.unwrap();
    for branch in branchs {
        if branch.is_err() {
            continue;
        }
        let branch = branch.unwrap();

        let name = branch.0.name();
        if name.is_err() {
            continue;
        }
        let name = name.unwrap().unwrap_or_default();

        let upstream = match branch.0.upstream() {
            Err(..) => String::from(""),
            Ok(up_branch) => {
                let name = up_branch.name();
                if name.is_err() {
                    String::from("")
                } else {
                    String::from(name.unwrap().unwrap_or_default())
                }
            }
        };

        let commit = branch.0.get().peel_to_commit();
        if commit.is_err() {
            return Err(commit.err().unwrap());
        }
        let commit = commit.unwrap();
        info_list.push(BranchInfo {
            name: String::from(name),
            upstream: upstream,
            commit_id: commit.id().to_string(),
            commit_summary: String::from(commit.message().unwrap_or_default()),
            commit_time: commit.time().seconds() * 1000,
        })
    }
    println!("{}", serde_json::to_string(&info_list).unwrap());
    return Ok(());
}
